const crypto = require('crypto');
const request = require('request');
const config = require('../config');

const appKey = config.uniApp.appKey;
const masterSecret = config.uniApp.secret;
const baseUrl = `https://restapi.getui.com/v2/${config.uniApp.appId}`;
const appService = require('../service/appService');
async function batchPush(cid, message) {
    const taskid = await createMessage(message).catch(async() => {
        await initPushToken();
        await batchPush(cid, message);
    });
    if (!taskid) {
        return;
    }
    const token = await getPushToken();
    request({
        url: `${baseUrl}/push/list/cid`,
        method: 'POST',
        headers: {
            'content-type': 'application/json;charset=UTF-8',
            token,
        },
        body: JSON.stringify({
            audience: {
                cid
            },
            taskid,
            is_async: true
        })
    }, function(error, res, body) {
        let data = JSON.parse(body);
        console.log(body);
        if (data.code === 10001) {
            // token过期，重新发送
            initPushToken();
            batchPush(cid, message);
        } else if (data.code === 0) {
            console.log('*********************发送成功***********************');
        }
    });
}

async function getPushToken() {
    const app = await appService.find();
    return app.pushToken;
}

// 创建消息
async function createMessage({ title, body }) {
    const token = await getPushToken();
    return new Promise((resolve, reject) => {
        request({
            url: `${baseUrl}/push/list/message`,
            method: 'POST',
            headers: {
                'content-type': 'application/json;charset=UTF-8',
                token
            },
            body: JSON.stringify({
                request_id: uuidGenerator(),
                group_name: 'newOrder',
                settings: {
                    ttl: 3600000
                },
                push_message: {
                    notification: {
                        title,
                        body,
                        click_type: 'startapp'
                    }
                }
            })
        }, function(error, res, body) {
            console.log(body);
            console.log('createMessage*************************');
            let data = JSON.parse(body);
            if (data.code === 0) {
                resolve(data.data.taskid);
            }
            reject();
        });
    })
}

function uuidGenerator() {
    const originStr = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        originChar = '0123456789abcdef',
        len = originChar.length;
    return originStr.replace(/x/g, function(match) {
        return originChar.charAt(Math.floor(Math.random() * len))
    }).replace(/-/g, '');
}

function getSign() {
    const sha256 = crypto.createHash('sha256');
    sha256.update(appKey + (new Date()).getTime() + masterSecret);
    return sha256.digest('hex');
}

function initPushToken() {
    return new Promise((resolve, reject) => {
        request({
            url: `${baseUrl}/auth`,
            method: 'POST',
            headers: {
                'content-type': 'application/json;charset=UTF-8'
            },
            body: JSON.stringify({
                sign: getSign(),
                timestamp: (new Date()).getTime(),
                appkey: appKey
            })
        }, async(error, res, body) => {
            let data = JSON.parse(body);
            if (data.code === 0) {
                // 保存token
                await appService.update({
                    pushToken: data.data.token
                })
                console.log('推送token获取完毕');
                resolve();
            }
            reject();
        });
    })
}

module.exports = {
    initPushToken,
    batchPush
}